import React, { useState, useContext } from "react";
import { withAuthServerSideProps } from "../../utils/withAuth";
import getConfig from "next/config";
import Box from "../../components/Box";
import Text from "../../components/Text";
import SEO from "../../components/SEO";
import Button from "../../components/Button";
import Infobox from "../../components/Infobox";
import { NotificationContext } from "../../components/Notifications";

// 简单的占位页面
const UpdateScores = ({ token, isAdmin }) => {
  const [isUpdating, setIsUpdating] = useState(false);
  const [result, setResult] = useState(null);
  const { addNotification } = useContext(NotificationContext);

  if (!isAdmin) {
    return (
      <>
        <SEO title="仅限管理员" />
        <Text as="h1">仅限管理员访问</Text>
        <Text>您没有权限访问此页面。</Text>
      </>
    );
  }

  const handleUpdateScores = async () => {
    try {
      setIsUpdating(true);
      setResult(null);

      const {
        publicRuntimeConfig: { SQ_API_URL },
      } = getConfig();

      const response = await fetch(`${SQ_API_URL}/torrent/update-all-scores`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${token}`,
        },
      });

      if (!response.ok) {
        throw new Error(`更新失败: ${response.status}`);
      }

      const data = await response.json();
      setResult(data);
      addNotification("success", `更新成功: ${data.message}`);
    } catch (error) {
      console.error("更新评分失败:", error);
      addNotification("error", `更新评分失败: ${error.message}`);
    } finally {
      setIsUpdating(false);
    }
  };

  return (
    <>
      <SEO title="更新种子评分" />
      <Text as="h1" mb={4}>
        种子评分管理
      </Text>

      <Infobox mb={4}>
        <Text mb={3}>
          这里可以手动触发所有种子的评分更新。根据种子数量，此操作可能需要几分钟时间。
        </Text>
        <Text>评分系统会计算三个维度的分数：</Text>
        <Box as="ul" pl={4} mt={2}>
          <li>
            <Text>技术维度 (30%): 包括下载成功率和资源健康度</Text>
          </li>
          <li>
            <Text>内容维度 (50%): 基于用户评分</Text>
          </li>
          <li>
            <Text>社区维度 (20%): 包括问题响应时间和长期价值</Text>
          </li>
        </Box>
      </Infobox>

      <Button
        onClick={handleUpdateScores}
        disabled={isUpdating}
        variant="primary"
      >
        {isUpdating ? "更新中..." : "更新所有种子评分"}
      </Button>

      {result && (
        <Box mt={4} p={4} bg="sidebar" borderRadius={2}>
          <Text fontWeight="bold" mb={2}>
            更新结果:
          </Text>
          <Text>成功更新: {result.updated} 个种子</Text>
          <Text>总种子数: {result.total} 个</Text>
          <Text mt={2}>更新时间: {new Date().toLocaleString()}</Text>
        </Box>
      )}
    </>
  );
};

export const getServerSideProps = withAuthServerSideProps(
  async ({ token, userRole }) => {
    return {
      props: {
        token,
        isAdmin: userRole === "admin",
      },
    };
  }
);

export default UpdateScores;
